﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web;

namespace Disclaimer.Layouts.Disclaimer
{
    public class SharepointManager
    {
        public static SPWeb GetCurrentWeb()
        {
            //SPSite site = new SPSite("http://localhost:50/");
            SPSite site = SPContext.Current.Site;
            SPWeb myWeb = site.OpenWeb();

            //to enable editing from this website
            myWeb.AllowUnsafeUpdates = true;

            return myWeb;
        }

        public static Guid CreateNewList(string listName, string listDescription, SPListTemplateType type)
        {
            Guid guid = Guid.Empty;
            try
            {
                SPWeb myWeb = GetCurrentWeb();
                guid = myWeb.Lists.Add(listName, listDescription, type);
                myWeb.Close();
            }
            catch { }
            return guid;
        }

        public static SPList GetList(string listName)
        {
            SPList list = null;
            try
            {
                SPWeb myWeb = GetCurrentWeb();
                list = myWeb.Lists[listName];
                myWeb.Close();
            }
            catch { }
            return list;
        }

        public static bool ManageList(string listName, SPField field)
        {
            bool success = false;
            SPList list = GetList(listName);
            if (list.Fields.GetField(field.InternalName) == null)
                list.Fields.Add(field);

            return success;
        }

        public static SPListItem GetListItem(int itemId, string listName)
        {
            SPList list = GetList(listName);
            if (list != null)
                return list.Items.GetItemById(itemId);
            else
                return null;
        }

        public static void UpdateItem(SPListItem listItem, string listName)
        {
            SPList list = GetList(listName);
        }

        public static bool ListExists(SPWeb web, string listName)
        {
            return web.Lists.Cast<SPList>().Any(list => string.Equals(list.Title, listName));
        }


        public static bool WebExists(SPSite site, string webName)
        {
            return site.AllWebs.Cast<SPWeb>().Any(web => string.Equals(web.Name, webName));
        }
    }
}
